package com.hhc.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hhc.dto.NoticeDTO;
import com.hhc.entity.NoticeAnnouncement;
import com.hhc.entity.UserInfo;
import com.hhc.query.NoticeQuery;
import com.hhc.query.UserQuery;
import com.hhc.repository.NoticeRepository;
import com.hhc.service.NoticeService;
import com.hhc.utils.RestResult;
import jakarta.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * <p>
 *   通知公告服务实现类
 * </p>
 * @author pc
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class NoticeServiceImpl implements NoticeService {

    private final NoticeRepository noticeRepository;
    private final ObjectMapper objectMapper;

    /**
     * 发布通知公告
     *
     * @param noticeDTO 公告信息
     * @return RestResult
     */
    @Override
    public RestResult<String> publish(NoticeDTO noticeDTO) {
        try {
            // 构建实体对象并保存
            NoticeAnnouncement entity = new NoticeAnnouncement();
            BeanUtils.copyProperties(noticeDTO, entity);
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setCreateBy("admin"); // 假设默认为管理员创建
            entity.setUpdateBy("admin");
            
            if (noticeDTO.getTargetGroup() != null && !noticeDTO.getTargetGroup().isEmpty()) {
                entity.setTargetGroup(objectMapper.writeValueAsString(noticeDTO.getTargetGroup()));
            } else {
                entity.setTargetGroup(null);
            }
            
            noticeRepository.save(entity);
            log.info("发布通知公告成功: {}", entity.getId());
            return RestResult.success("调用成功");
        } catch (Exception e) {
            log.error("发布通知公告失败", e);
            return RestResult.failed("发布失败");
        }
    }

//    /**
//     * 查询用户列表（支持条件搜索和分页）
//     */
//    @Override
//    public RestResult<Object> list(UserQuery query) {
//        try {
//            // 创建分页条件
//            Pageable pageable = PageRequest.of(query.getCurrentPage() - 1, query.getPageSize());
//
//            // 执行条件查询
//            Page<UserInfo> userPage = userInfoRepository.findByCondition(
//                    query.getUsername(),  // 用户名模糊查询
//                    query.getEmail(),     // 邮箱模糊查询
//                    query.getPhone(),     // 手机号模糊查询
//                    pageable              // 分页参数
//            );
//
//            // 构建返回结果
//            Map<String, Object> result = new HashMap<>();
//            result.put("currentPage", query.getCurrentPage());
//            result.put("pageSize", query.getPageSize());
//            result.put("total", userPage.getTotalElements());  // 总条数
//            result.put("data", userPage.getContent());         // 当前页数据
//
//            return RestResult.success(result);
//        } catch (Exception e) {
//            log.error("查询用户列表失败", e);
//            return RestResult.failed("查询失败");
//        }
//    }

    /**
     * 查询通知公告列表
     *
     * @param query 查询参数
     * @return RestResult
     */
    @Override
    public RestResult<Object> list(NoticeQuery query) {
        try {
            Pageable pageable = PageRequest.of(query.getCurrentPage()-1, query.getPageSize());
            Map<String, Object> result = new HashMap<>();
            result.put("currentPage", query.getCurrentPage());
            result.put("pageSize", query.getPageSize());

            // 获取符合条件的数据
            LocalDateTime now = LocalDateTime.now();
            Iterable<NoticeAnnouncement> notices = noticeRepository.findActiveNotices(now, 1); // 只查激活的

            result.put("total", 0); // 实际总数量需要从数据库获取或缓存中读取
            result.put("data", notices);
            return RestResult.success(result);
        } catch (Exception e) {
            log.error("查询通知公告列表失败", e);
            return RestResult.failed("查询失败");
        }
    }

    /**
     * 获取通知公告详情
     *
     * @param id 公告ID
     * @return RestResult
     */
    @Override
    public RestResult<Object> detail(Long id) {
        try {
            NoticeAnnouncement notice = noticeRepository.findById(id).orElse(null);
            if (notice == null || notice.getIsActive() == 0) {
                return RestResult.failed("公告不存在");
            }

            // 如果目标群体有值，则解析回List
            if (notice.getTargetGroup() != null && !notice.getTargetGroup().isEmpty()) {
                try {
                    notice.setTargetGroup(objectMapper.readValue(notice.getTargetGroup(), String.class));
                } catch (Exception ignored) {}
            }

            return RestResult.success(notice);
        } catch (Exception e) {
            log.error("获取通知公告详情失败", e);
            return RestResult.failed("获取失败");
        }
    }

    /**
     * 更新通知公告
     *
     * @param id 公告ID
     * @param noticeDTO 更新信息
     * @return RestResult
     */
    @Override
    public RestResult<String> update(Long id, NoticeDTO noticeDTO) {
        try {
            NoticeAnnouncement existing = noticeRepository.findById(id).orElse(null);
            if (existing == null || existing.getIsActive() == 0) {
                return RestResult.failed("公告不存在");
            }

            BeanUtils.copyProperties(noticeDTO, existing);
            existing.setUpdateTime(LocalDateTime.now());

            if (noticeDTO.getTargetGroup() != null && !noticeDTO.getTargetGroup().isEmpty()) {
                existing.setTargetGroup(objectMapper.writeValueAsString(noticeDTO.getTargetGroup()));
            } else {
                existing.setTargetGroup(null);
            }

            noticeRepository.save(existing);
            log.info("更新通知公告成功: {}", id);
            return RestResult.success("调用成功");
        } catch (Exception e) {
            log.error("更新通知公告失败", e);
            return RestResult.failed("更新失败");
        }
    }

    /**
     * 删除通知公告
     *
     * @param id 公告ID
     * @return RestResult
     */
    @Override
    public RestResult<String> delete(Long id) {
        try {
            NoticeAnnouncement existing = noticeRepository.findById(id).orElse(null);
            if (existing == null || existing.getIsActive() == 0) {
                return RestResult.failed("公告不存在");
            }

            existing.setIsActive(0); // 标记为无效
            existing.setUpdateTime(LocalDateTime.now());
            noticeRepository.save(existing);
            log.info("删除通知公告成功: {}", id);
            return RestResult.success("调用成功");
        } catch (Exception e) {
            log.error("删除通知公告失败", e);
            return RestResult.failed("删除失败");
        }
    }
}